<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="姓名" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教师姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工号" prop="teacherNo">
        <el-input
          v-model="queryParams.teacherNo"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职务" prop="position">
        <el-input
          v-model="queryParams.position"
          placeholder="请输入职务"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="学历" prop="educationLevel">
        <el-input
          v-model="queryParams.educationLevel"
          placeholder="请输入学历"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职称" prop="professionalTitle">
        <el-input
          v-model="queryParams.professionalTitle"
          placeholder="请输入职称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['ao:teacher:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ao:teacher:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 删除功能已移除，防止误删重要的教师基础数据 -->
        <!-- <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['ao:teacher:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="教师ID" align="center" prop="teacherId" width="80" />
      <el-table-column label="姓名" align="center" prop="teacherName" width="100" />
      <el-table-column label="工号" align="center" prop="teacherNo" width="120" />
      <el-table-column label="职务" align="center" prop="position" width="120" />
      <el-table-column label="性别" align="center" prop="gender" width="60">
        <template #default="scope">
          <el-tag :type="scope.row.gender === 1 ? 'primary' : 'success'">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" width="60" />
      <el-table-column label="联系方式" align="center" prop="contactPhone" width="130" />
      <el-table-column
        label="入职日期"
        align="center"
        prop="entryDate"
        :formatter="dateFormatter2"
        width="120"
      />
      <el-table-column label="已满年限" align="center" prop="serviceYears" width="100" />
      <el-table-column
        label="合同到期"
        align="center"
        prop="contractExpireDate"
        :formatter="dateFormatter2"
        width="120"
      />
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
            link
            type="info"
            @click="showTeacherDetail(scope.row)"
            v-hasPermi="['ao:teacher:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.teacherId)"
            v-hasPermi="['ao:teacher:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="showTeacherSchedule(scope.row)"
            v-hasPermi="['ao:teacher:query']"
          >
            课程表
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TeacherForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：导入 -->
  <TeacherImportForm ref="importFormRef" @success="getList" />

  <!-- 教师详情弹窗 -->
  <el-dialog
    v-model="detailDialogVisible"
    :title="`${selectedTeacher?.teacherName} 的详细信息`"
    width="70%"
    :before-close="handleDetailDialogClose"
  >
    <div v-if="selectedTeacher" class="teacher-detail">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="detail-section">
            <h4>基本信息</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="姓名">{{ selectedTeacher.teacherName }}</el-descriptions-item>
              <el-descriptions-item label="工号">{{ selectedTeacher.teacherNo }}</el-descriptions-item>
              <el-descriptions-item label="职务">{{ selectedTeacher.position }}</el-descriptions-item>
              <el-descriptions-item label="性别">
                {{ selectedTeacher.gender === 1 ? '男' : selectedTeacher.gender === 2 ? '女' : '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="年龄">{{ selectedTeacher.age }}</el-descriptions-item>
              <el-descriptions-item label="婚否">
                {{ selectedTeacher.maritalStatus === 1 ? '已婚' : selectedTeacher.maritalStatus === 0 ? '未婚' : '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="民族">{{ selectedTeacher.ethnicity }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ selectedTeacher.idCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ selectedTeacher.contactPhone }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="detail-section">
            <h4>日期信息</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="出生日期">{{ formatDate(selectedTeacher.birthDate) }}</el-descriptions-item>
              <el-descriptions-item label="入职日期">{{ formatDate(selectedTeacher.entryDate) }}</el-descriptions-item>
              <el-descriptions-item label="入职年份">{{ selectedTeacher.entryYear }}</el-descriptions-item>
              <el-descriptions-item label="入职月份">{{ selectedTeacher.entryMonth }}</el-descriptions-item>
              <el-descriptions-item label="已满年限">{{ selectedTeacher.serviceYears }}</el-descriptions-item>
              <el-descriptions-item label="毕业时间">{{ formatDate(selectedTeacher.graduationDate) }}</el-descriptions-item>
              <el-descriptions-item label="签订合同">{{ formatDate(selectedTeacher.contractSignDate) }}</el-descriptions-item>
              <el-descriptions-item label="合同到期">{{ formatDate(selectedTeacher.contractExpireDate) }}</el-descriptions-item>
              <el-descriptions-item label="证书颁发日期">{{ formatDate(selectedTeacher.certificateIssueDate) }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <div class="detail-section">
            <h4>教育背景</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="学历">{{ selectedTeacher.educationLevel }}</el-descriptions-item>
              <el-descriptions-item label="专业">{{ selectedTeacher.major }}</el-descriptions-item>
              <el-descriptions-item label="毕业学校">{{ selectedTeacher.graduateSchool }}</el-descriptions-item>
              <el-descriptions-item label="专业证书">{{ selectedTeacher.professionalCertificate }}</el-descriptions-item>
              <el-descriptions-item label="教资证书编码">{{ selectedTeacher.teachingCertificateNo }}</el-descriptions-item>
              <el-descriptions-item label="颁发单位">{{ selectedTeacher.certificateIssuer }}</el-descriptions-item>
              <el-descriptions-item label="职称">{{ selectedTeacher.professionalTitle }}</el-descriptions-item>
              <el-descriptions-item label="职业等级">{{ selectedTeacher.professionalLevel }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="detail-section">
            <h4>其他信息</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="户口类型">{{ selectedTeacher.householdType }}</el-descriptions-item>
              <el-descriptions-item label="籍贯">{{ selectedTeacher.nativePlace }}</el-descriptions-item>
              <el-descriptions-item label="户籍地址">{{ selectedTeacher.householdAddress }}</el-descriptions-item>
              <el-descriptions-item label="现住地址">{{ selectedTeacher.currentAddress }}</el-descriptions-item>
              <el-descriptions-item label="社保">{{ selectedTeacher.socialInsurance }}</el-descriptions-item>
              <el-descriptions-item label="紧急联系">{{ selectedTeacher.emergencyContact }}</el-descriptions-item>
              <el-descriptions-item label="个人邮箱">{{ selectedTeacher.personalEmail }}</el-descriptions-item>
              <el-descriptions-item label="QQ号">{{ selectedTeacher.qqNumber }}</el-descriptions-item>
              <el-descriptions-item label="政治面貌">{{ selectedTeacher.politicalStatus }}</el-descriptions-item>
              <el-descriptions-item label="人事异动">{{ selectedTeacher.personnelChanges }}</el-descriptions-item>
              <el-descriptions-item label="爱好及特长">{{ selectedTeacher.hobbiesSpecialties }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>

  <!-- 教师课程表弹窗 -->
  <el-dialog v-model="scheduleDialogVisible" :title="`${selectedTeacher?.teacherName || '教师'}的课程表`" width="90%" top="5vh">
    <div v-loading="scheduleLoading">
      <div class="mb-4">
        <el-tag type="info" size="large">{{ selectedTeacher?.teacherName || '未知教师' }}</el-tag>
        <el-tag v-if="selectedTeacher?.subject" type="primary" size="large" class="ml-2">
          主要科目：{{ selectedTeacher.subject }}
        </el-tag>
      </div>

      <div v-if="scheduleData.length > 0">
        <el-table :data="scheduleData" border style="width: 100%" class="schedule-table">
          <el-table-column prop="section" label="节次" width="120" align="center" />
          <el-table-column prop="monday" label="周一" align="center">
            <template #default="scope">
              <div v-if="scope.row.monday" class="course-cell">
                {{ scope.row.monday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tuesday" label="周二" align="center">
            <template #default="scope">
              <div v-if="scope.row.tuesday" class="course-cell">
                {{ scope.row.tuesday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="wednesday" label="周三" align="center">
            <template #default="scope">
              <div v-if="scope.row.wednesday" class="course-cell">
                {{ scope.row.wednesday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="thursday" label="周四" align="center">
            <template #default="scope">
              <div v-if="scope.row.thursday" class="course-cell">
                {{ scope.row.thursday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="friday" label="周五" align="center">
            <template #default="scope">
              <div v-if="scope.row.friday" class="course-cell">
                {{ scope.row.friday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="saturday" label="周六" align="center">
            <template #default="scope">
              <div v-if="scope.row.saturday" class="course-cell">
                {{ scope.row.saturday }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="sunday" label="周日" align="center">
            <template #default="scope">
              <div v-if="scope.row.sunday" class="course-cell">
                {{ scope.row.sunday }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-else class="text-center text-gray-500 py-8">
        <el-empty description="该教师暂无课程安排" />
      </div>
    </div>

    <template #footer>
      <el-button @click="scheduleDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.schedule-table {
  font-size: 14px;
}

.course-cell {
  padding: 8px;
  background-color: #f0f9ff;
  border-radius: 4px;
  white-space: pre-line;
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  line-height: 1.4;
}

.course-cell:hover {
  background-color: #e0f2fe;
  transform: translateY(-1px);
  transition: all 0.2s ease;
}
</style>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TeacherApi, Teacher } from '@/api/ao/teacher'
import TeacherForm from './TeacherForm.vue'
import TeacherImportForm from './TeacherImportForm.vue'
import dayjs from 'dayjs'

/** 教师信息 列表 */
defineOptions({ name: 'Teacher' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Teacher[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptName: undefined,
  teacherName: undefined,
  teacherNo: undefined,
  position: undefined,
  gender: undefined,
  maritalStatus: undefined,
  educationLevel: undefined,
  major: undefined,
  graduateSchool: undefined,
  entryDate: [],
  professionalTitle: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 课程表弹窗相关
const scheduleDialogVisible = ref(false) // 课程表弹窗显示状态
const scheduleLoading = ref(false) // 课程表加载状态
const selectedTeacher = ref<Teacher | null>(null) // 选中的教师
const scheduleData = ref<any[]>([]) // 课程表数据

// 详情弹窗相关
const detailDialogVisible = ref(false) // 详情弹窗显示状态

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TeacherApi.getTeacherPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 删除功能已移除，防止误删重要的教师基础数据
// /** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await TeacherApi.deleteTeacher(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {}
// }

// /** 批量删除教师信息 */
// const handleDeleteBatch = async () => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     await TeacherApi.deleteTeacherList(checkedIds.value);
//     message.success(t('common.delSuccess'))
//     await getList();
//   } catch {}
// }

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Teacher[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TeacherApi.exportTeacher(queryParams)
    download.excel(data, '教师信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入按钮操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 显示教师详情 */
const showTeacherDetail = (teacher: Teacher) => {
  selectedTeacher.value = teacher
  detailDialogVisible.value = true
}

/** 关闭详情弹窗 */
const handleDetailDialogClose = () => {
  detailDialogVisible.value = false
  selectedTeacher.value = null
}

/** 格式化日期显示 */
const formatDate = (date: string | null) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

/** 查看教师课程表 */
const showTeacherSchedule = async (teacher: Teacher) => {
  selectedTeacher.value = teacher
  scheduleDialogVisible.value = true
  scheduleLoading.value = true
  scheduleData.value = []

  try {
    const data = await TeacherApi.getTeacherSchedule(teacher.teacherId)
    if (data && data.scheduleGrid) {
      scheduleData.value = data.scheduleGrid
    }
  } catch (error) {
    console.error('获取教师课程表失败:', error)
    message.error('获取教师课程表失败')
  } finally {
    scheduleLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.teacher-detail {
  padding: 10px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #409eff;
  border-bottom: 2px solid #409eff;
  padding-bottom: 5px;
}

.el-descriptions {
  margin-bottom: 15px;
}

.el-descriptions-item__label {
  font-weight: bold;
  width: 120px;
}
</style>
